package com.example.consumer.config;

import com.netflix.loadbalancer.RandomRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * description: RestTemplateConfig <br>
 * date: 2021/5/25 11:58 <br>
 * author: xiehui <br>
 * version: 1.0 <br>
 */
@Configuration
public class RestTemplateConfig {

    /**
     * 基于OkHttp3配置RestTemplate,
     * 默认springboot是没有注入RestTemplate，所以需要的话需要手动注入
     */
    @Bean("restTemplate")
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

    @Bean
    public RandomRule randomRule() {
        return new RandomRule();
    }

    @Bean("restTemplateByLoadBalanced")
    @LoadBalanced // 负载均衡
    public RestTemplate restTemplateByLoadBalanced() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }
}
